from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from .models import Workflow, WorkflowInstance
from .serializers import WorkflowSerializer, WorkflowInstanceSerializer
from .services import WorkflowEngine

class WorkflowViewSet(viewsets.ModelViewSet):
    queryset = Workflow.objects.all()
    serializer_class = WorkflowSerializer
    
    @action(detail=True, methods=['post'])
    def start_instance(self, request, pk=None):
        workflow = self.get_object()
        instance = WorkflowEngine.create_workflow_instance(workflow, request.user)
        return Response(WorkflowInstanceSerializer(instance).data)

class WorkflowInstanceViewSet(viewsets.ModelViewSet):
    queryset = WorkflowInstance.objects.all()
    serializer_class = WorkflowInstanceSerializer
    
    @action(detail=True, methods=['post'])
    def process(self, request, pk=None):
        instance = self.get_object()
        WorkflowEngine.process_node(instance, request.data)
        return Response(self.serializer_class(instance).data) 